package com.shinhye.mobilelottery.ui;

import org.apache.commons.lang3.StringUtils;

import android.content.Context;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

import com.shinhye.mobilelottery.ConstantValue;
import com.shinhye.mobilelottery.GlobalParams;
import com.shinhye.mobilelottery.R;
import com.shinhye.mobilelottery.bean.ShoppingCart;
import com.shinhye.mobilelottery.bean.Ticket;
import com.shinhye.mobilelottery.bean.User;
import com.shinhye.mobilelottery.engine.UserEngine;
import com.shinhye.mobilelottery.net.protocol.Message;
import com.shinhye.mobilelottery.net.protocol.Oelement;
import com.shinhye.mobilelottery.net.protocol.element.BetElement;
import com.shinhye.mobilelottery.ui.manager.MiddleManager;
import com.shinhye.mobilelottery.ui.manager.TitleManager;
import com.shinhye.mobilelottery.utils.BeanFactory;
import com.shinhye.mobilelottery.utils.PromptManager;

public class PreBetUI extends BaseUI implements OnClickListener{
	private TextView bettingNum;// 注数
	private TextView bettingMoney;// 金额
	private Button subAppnumbers;// 减少倍投
	private TextView appnumbersInfo;// 倍数
	private Button addAppnumbers;// 增加倍投
	private Button subIssueflagNum;// 减少追期
	private TextView issueflagNumInfo;// 追期
	private Button addIssueflagNum;// 增加追期
	private ImageButton lotteryPurchase;// 投注
	private ListView shoppingList;// 购物车展示
	private MyAdapter adapter;
	private ShoppingCart shoppingCart;

	/*
	 	// 工作清单
		// ①填充ListView
		// ②处理提示（高亮）
		// ③追期和倍投的设置
		// ④投注
	 */
	public PreBetUI(Context context) {
		super(context);
	}

	@Override
	protected void onCreate() {
		shoppingCart = ShoppingCart.getInstance();
		View showView = View.inflate(getContext(), R.layout.il_play_prefectbetting, null);
		
		bettingNum = (TextView) showView.findViewById(R.id.ii_shopping_list_betting_num);
		bettingMoney = (TextView) showView.findViewById(R.id.ii_shopping_list_betting_money);

		subAppnumbers = (Button) showView.findViewById(R.id.ii_sub_appnumbers);
		appnumbersInfo = (TextView) showView.findViewById(R.id.ii_appnumbers);
		addAppnumbers = (Button) showView.findViewById(R.id.ii_add_appnumbers);

		subIssueflagNum = (Button) showView.findViewById(R.id.ii_sub_issueflagNum);
		issueflagNumInfo = (TextView) showView.findViewById(R.id.ii_issueflagNum);
		addIssueflagNum = (Button) showView.findViewById(R.id.ii_add_issueflagNum);

		lotteryPurchase = (ImageButton) showView.findViewById(R.id.ii_lottery_purchase);
		shoppingList = (ListView) showView.findViewById(R.id.ii_lottery_shopping_list);

		adapter = new MyAdapter();
		shoppingList.setAdapter(adapter);
		setContentView(showView);
	}
	
	class MyAdapter extends BaseAdapter {
		@Override
		public int getCount() {
			return shoppingCart.getTicketBag().size();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if(convertView == null) {
				convertView = View.inflate(getContext(), R.layout.il_play_prefectbetting_row, null);
				ViewHolder holder = new ViewHolder();
				holder.red = (TextView) convertView.findViewById(R.id.ii_shopping_item_reds);
				holder.blue = (TextView) convertView.findViewById(R.id.ii_shopping_item_blues);
				convertView.setTag(holder);
			}
			ViewHolder holder = (ViewHolder) convertView.getTag();
			Ticket ticket = shoppingCart.getTicketBag().get(position);
			holder.red.setText(ticket.getRedNum());
			holder.blue.setText(ticket.getBlueNum());
			return convertView;
		}
		
		@Override
		public Object getItem(int position) {
			return shoppingCart.getTicketBag().get(position);
		}
		@Override
		public long getItemId(int position) {
			return position;
		}
	}

	static class ViewHolder {
		TextView red;
		TextView blue;
	}

	@Override
	protected void setListener() {
		// 倍数
		addAppnumbers.setOnClickListener(this);
		subAppnumbers.setOnClickListener(this);
		// 追期
		addIssueflagNum.setOnClickListener(this);
		subIssueflagNum.setOnClickListener(this);
		// 投注
		lotteryPurchase.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch(v.getId()) {
		case R.id.ii_add_appnumbers:
			// 增加倍数
			if(shoppingCart.changeAppnumbers(true)) {
				changeNotice();
			}
			break;
		case R.id.ii_sub_appnumbers:
			// 减少倍数
			if(shoppingCart.changeAppnumbers(false)) {
				changeNotice();
			}
			break;
		case R.id.ii_add_issueflagNum:
			// 增加追期
			if(shoppingCart.changeIssuesnumbers(true)) {
				changeNotice();
			}
			break;
		case R.id.ii_sub_issueflagNum:
			// 减少追期
			if(shoppingCart.changeIssuesnumbers(false)) {
				changeNotice();
			}
			break;
		case R.id.ii_lottery_purchase:
			// 购买
			User user = new User();
			new MyAsyncTask<User>() {
				@Override
				protected void onPreExecute() {
					PromptManager.showProgressDialog(getContext());
				};

				@Override
				protected Message doInBackground(User... params) {
					User user = params[0];
					UserEngine engine = BeanFactory.getImpl(UserEngine.class);
					Message res = engine.bet(user);
					return res;
				}
				
				@Override
				protected void onPostExecute(Message result) {
					PromptManager.closeProgressDialog();
					if(result == null) {
						PromptManager.showToast(getContext(), "投注失败！请稍后重试！");
						return;
					}
					
					Oelement oelement = result.getBody().getOelement();
					if(ConstantValue.SUCCESS.equals(oelement.getErrorcode())) {
						BetElement element = (BetElement) result.getBody().getElements().get(0);
						GlobalParams.money = Float.parseFloat(element.getActvalue());
						
						shoppingCart.clear();
						MiddleManager.getInstance().clear();
						
						MiddleManager.getInstance().changeUI(HallUI.class, null);
						PromptManager.showErrorDialog(getContext(), "投注成功");
						
						//XXX
						// 问题列表
						// 1、购彩大厅界面标题内容需要修改
						// 2、清理返回键
						// 3、购物车的数据清理
					}
				};
			}.executeHttp(user);
			
			break;

		}
	}

	@Override
	public int getId() {
		return ConstantValue.VIEW_PREBET;
	}
	
	@Override
	public void onResume() {
		changeTitle();
		changeNotice();
	}

	private void changeNotice() {
		int lotterynumber = ShoppingCart.getInstance().getLotterynumber();
		int lotteryvalue = ShoppingCart.getInstance().getLotteryvalue();

		String numStr = getContext().getResources().getString(R.string.is_shopping_list_betting_num);
		numStr = StringUtils.replace(numStr, "NUM", lotterynumber + "");
		bettingNum.setText(Html.fromHtml(numStr));

		String moneyStr = getContext().getResources().getString(R.string.is_shopping_list_betting_money);
		moneyStr = StringUtils.replaceEach(moneyStr, new String[] { "MONEY1", "MONEY2" }, new String[] { lotteryvalue + "", GlobalParams.money + "" });
		bettingMoney.setText(Html.fromHtml(moneyStr));

		int appnumbers = ShoppingCart.getInstance().getAppnumbers();
		int issuesnumbers = ShoppingCart.getInstance().getIssuesnumbers();

		// 追期和倍数的提示
		appnumbersInfo.setText(appnumbers + "");
		issueflagNumInfo.setText(issuesnumbers + "");

	}

	private void changeTitle() {
		Bundle bundle = getBundle();
		String issue = "";
		String title = "";
		if(bundle != null) {
			issue = bundle.getString("issue");
		}
		if(TextUtils.isEmpty(issue)) {
			title = "双色球选号";
		} else {
			title = "双色球第" + bundle.getString("issue") + "期选号";
		}
		TitleManager.getInstance().changeTitle(title);
	}
}
